package servlet.pack1009;

import bean.GoodsInfo;
import biz.GoodsBiz;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    private GoodsBiz gb = new GoodsBiz();
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String type = request.getParameter("type");
        if (type==null||"find".equals(type)){
            find(request,response);
        }else if ("delete".equals(type)){
            delete(request,response);
        }
    }
    private void find(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        HttpSession session = request.getSession();
        session.setAttribute("ALL_GOODS_LIST",gb.findAllGoods());
        response.sendRedirect("1009/gwc.jsp");
    }
    private void delete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        HttpSession session = request.getSession();
        List<GoodsInfo> list = (List<GoodsInfo>) session.getAttribute("GWC_LIST");
        int id = Integer.parseInt(request.getParameter("id"));
        System.out.println(id+"*****");
        GoodsInfo gi = gb.findGoodsById(id);
        System.out.println(gi+"(**&&");
        boolean b = list.remove(gi);
        System.out.println(b);
        session.setAttribute("GWC_LIST",list);
        response.sendRedirect("1009/gwc.jsp");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        List<GoodsInfo> list ;
        Object obj = session.getAttribute("GWC_LIST");
        if(obj==null){
            list = new ArrayList<>();
        }else{
            list = (List<GoodsInfo>) obj;
        }
        String[] ids = request.getParameterValues("ids");
        for(String s:ids){
            int id = Integer.parseInt(s);
            GoodsInfo gi = gb.findGoodsById(id);
            int index = list.indexOf(gi);
            if(index==-1){
                list.add(gi);
            }else{
                GoodsInfo g = list.get(index);
                g.setGoodsUnm(g.getGoodsUnm()+1);
            }
        }
        session.setAttribute("GWC_LIST",list);
        response.sendRedirect("1009/index.jsp");
    }
}
